// pages/zkxinhe/index/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    ui: {
      topImgSrc: "https://ai.seedlight.cn:31000/iot-web-manage/img/home-logo.8be66afc.svg"
    },
    apiUrl: "https://ai.seedlight.cn:31000/api/seedlight/",
    ds: [1, 2, 3, 4, 5, 6],
    grains: [],
    dicts: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(options)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    var me = this;
    try {
      /*
      var updateUi = () => {
        me.refresh().then(res => {
          me.setData({
            grains: res.grains
          });
          setTimeout(() => {
            updateUi();
          }, 100000);
        })
      }
      */
      me.refresh().then(res => {
        me.setData({
          grains: res.grains
        });
      })
    } catch (error) {
      console.log(error);
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },


  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  getDatas(dataUrl, dataPs) {
    var me = this;
    return new Promise((success, faild) => {
      try {
        wx.request({
          url: dataUrl,
          method: "POST",
          data: dataPs,
          complete: (res) => {
            console.log(res);
            success(res.data.body);
          }
        })
      } catch (error) {
        console.log(error);
        success();
      }
    })
  },
  dateFormat(date, fmt) { // author: meizz
    var o = {
      'M+': date.getMonth() + 1, // 月份
      'd+': date.getDate(), // 日
      'H+': date.getHours(), // 小时
      'm+': date.getMinutes(), // 分
      's+': date.getSeconds(), // 秒
      'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
      S: date.getMilliseconds() // 毫秒
    }
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
    for (var k in o) {
      if (new RegExp('(' + k + ')').test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
    }
    return fmt
  },
  refresh() {
    var me = this;
    return new Promise((success, faild) => {
      try {
        var u0 = 'https://ai.seedlight.cn:31000/api/seedlight/getGrainList';
        var p0 = {
          code: "getGrainList",
          start: 0,
          end: 1000
        };
        var u1 = 'https://ai.seedlight.cn:31000/api/seedlight/getBarnList';
        var p1 = {
          code: "getBarnList",
          start: 0,
          end: 1000
        };
        var u2 = 'https://ai.seedlight.cn:31000/api/seedlight/getDeviceList';
        var p2 = {
          code: "getDeviceList",
          start: 0,
          end: 1000
        };
        var dicts = {
          devices: {}
        };
        var datas = {
          grains: [],
          bams: [],
          devices: []
        }
        me.getDatas(u0, p0).then(res => {
          datas.grains = res;
          return me.getDatas(u1, p1);
        }).then(res => {
          datas.bams = res;
          datas.grains.forEach(g => {
            g.bams = res.filter(b => {
              return g.grainId == b.grainId;
            })
          })
          return me.getDatas(u2, p2);
        }).then(res => {
          res.forEach(r => {
            try {
              dicts.devices[r.snCode] = r;
              r.imgtm = "";
              r.volt = (r.volt * 0.001).toFixed(2);
              r.cur = (r.cur * 0.001).toFixed(2);
              var t = r.imageUrl.split('_')[1];
              t = t.split('.')[0];
              var tm = new Date(parseInt(t) * 1000);
              r.imgtm = me.dateFormat(tm, 'yyyy-MM-dd HH:mm:ss');
            } catch (error) {
              console.log(error);
            }
            //r.imgUrl = 'https://ai.seedlight.cn:31000/images/20fb36d9e1476642_1663377016.jpg';
          })
          datas.devices = res;
          datas.bams.forEach(b => {
            b.devices = res.filter(d => {
              return b.barnId == d.barnId;
            })
          })

          var bams = datas.bams.filter(b => {
            return b.devices.length > 0;
          })
          datas.grains.forEach(g => {
            g.bams = bams.filter(b => {
              return b.grainId == g.grainId;
            })
          })
          var grains = datas.grains.filter(g => {
            return g.bams.length > 0;
          })

          datas.grains = grains;
          me.data.dicts = dicts;
          success(datas)
        })
      } catch (error) {
        console.log(error);
        success(null)
      }
    })
  },
  switchShowSettings(e) {
    var me = this;
    try {
      var gind = parseInt(e.target.dataset['gind']);
      var bind = parseInt(e.target.dataset['bind']);
      var dind = parseInt(e.target.dataset['dind']);
      var snCode = e.target.dataset['sncode'];
      var dev = me.data.grains[gind].bams[bind].devices[dind];
      if (dev.showSettings && dev.showSettings == 1) {
        dev.showSettings = 0;
      } else {
        dev.showSettings = 1;
      }
      me.setData({
        grains: JSON.parse(JSON.stringify(me.data.grains))
      });
    } catch (error) {
      console.log(error);
    }
  },
  acLight(e) {
    var me = this;
    try {
      var gind = parseInt(e.target.dataset['gind']);
      var bind = parseInt(e.target.dataset['bind']);
      var dind = parseInt(e.target.dataset['dind']);
      var flag = parseInt(e.target.dataset['flag']);
      var dev = me.data.grains[gind].bams[bind].devices[dind];
      var snCode = dev.snCode;
      var apiUrl = me.data.apiUrl + "setLightStatus";
      console.log(apiUrl);
      me.getDatas(apiUrl, {
        deviceId: snCode,
        light: flag
      }).then(res => {
        console.log(res);
      })
    } catch (error) {
      console.log(error);
    }
  }
})